package com.mju.listener;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.mju.model.ErrRow;
import com.mju.model.Teacher;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExcelTeacherListener extends AnalysisEventListener<Teacher> {

	private List<Teacher> list = new ArrayList<>();// 导入的数据
	private List<ErrRow> errList = new ArrayList<>();// 错误行列表

	@Override
	public void invoke(Teacher data, AnalysisContext context) {

		if (checkTeacherNo(data, context.readRowHolder().getRowIndex()))
			list.add(data);
		// log.info(context.readRowHolder().getRowIndex().toString());
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		log.info("*******************");
	}

	public List<Teacher> getList() {
		return this.list;
	}

	public List<ErrRow> getErrList() {
		return errList;
	}

	private boolean checkTeacherNo(Teacher data, int rowNum) {
		if ((data.getLimitnum() == null) || (data.getLimitnum() == 0)) {
			ErrRow err = new ErrRow(rowNum, "指导数目不能为空或0");
			errList.add(err);
			return false;
		}
		if (!StringUtils.hasText(data.getTeachername())) {
			ErrRow err = new ErrRow(rowNum, "指导导师不能为空");
			errList.add(err);
			return false;
		}
		if (!StringUtils.hasText(data.getMemo())) {
			ErrRow err = new ErrRow(rowNum, "指导内容不能为空");
			errList.add(err);
			return false;
		}

		// 判断工号或教师姓名是否重复
		for (Teacher each : list) {
			if (each.getTeachername().equals(data.getTeachername())
					|| each.getTeacherno().equals(data.getTeacherno())) {
				ErrRow err = new ErrRow(rowNum, "工号或姓名不能重复");
				errList.add(err);
				return false;
			}
		}
		return true;
	}
}
